package shujujiegou.Dongtaishuzu;

import java.util.Arrays;
import java.util.Iterator;
import java.util.function.Consumer;
import java.util.stream.IntStream;

public class DynamicArray implements Iterable<Integer> {
    private int size = 0;//逻辑大小
    private int capacity = 8;//容量
    private int[] array = {};

    //添加元素
    public void addLast(int element) {
        add(size, element);
    /*    array[size] = element;
        size++;*/
    }

    //插入元素
    public void add(int index, int element) {

        extracted();//用于扩容
        if (index >= 0 && index < size) {
            System.arraycopy(array, index, array, index + 1, size - index);
            array[index] = element;

        } else if (index == size) {
            array[index] = element;
        }
        size++;


    }

    private void extracted() {
        if (size==0){
            array=new int[capacity];
        }//对容量进行初始化，运用懒加载的思想

        else if (size==capacity){
            capacity+=capacity>>1;
            int[] NewArray = new int[capacity];
            System.arraycopy(array,0,
                    NewArray,0,size);
            array=NewArray;
        }
    }
    //用于删除某个方法
    public int remove(int index) {
        int removed = array[index];
        if (index<size-1){
        //需要移动得，起始位置，移动到得，起始位置，移动多少个元素
        System.arraycopy(array, index + 1,
                array, index, size - index - 1);}
        size--;
        return removed;
    }

    public int get(int index) {
        return array[index];
    }

    //ps：泛型只能用包装类型，不能用基本类型
    //遍历方法1
    public void foreach(Consumer<Integer> consumer) {
        for (int i = 0; i < size; i++) {
            consumer.accept(array[i]);
        }
    }

    //遍历方法2：迭代器遍历
    @Override
    public Iterator<Integer> iterator() {
        return new Iterator<Integer>() {
            int i = 0;

            @Override
            public boolean hasNext() {//有没有下一个元素
                return i < size;
            }

            @Override
            public Integer next() {//返回当前元素，并且指向下一个元素
                return array[i++];//先返回再自增
            }
        };
    }

    //遍历方法3

    public IntStream stream() {
        return IntStream.of(Arrays.copyOfRange(array, 0, size));
    }


}
